package org.jeecg.modules.extbpm.process.controller;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.dto.message.TemplateMessageDTO;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.CommonSendStatus;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.modules.extbpm.process.pojo.RoleInfo;
import org.jeecg.modules.extbpm.process.pojo.UserInfo;
import org.jeecg.modules.extbpm.process.service.IExtActProcessService;
import org.jeecg.modules.extbpm.process.service.impl.ExtActProcessServiceImpl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
*  同步流程用户
* @Return:
*/
@Slf4j
public class SyncUserThreadTask implements ThreadTask {
	private static final long serialVersionUID = 1L;
	
	public static String syncUserFlag = "0";
	private String username = "";

	public SyncUserThreadTask(String username){
		this.username = username;
	}


	@Override
	public Boolean call() {
		try {
			log.info("-----SyncUserThreadTask-----同步开始------");
			log.info("-----SyncUserThreadTask--syncUserFlag---------"+syncUserFlag);
			BaseCommonService baseCommonService = SpringContextUtils.getBean(BaseCommonService.class);
			ISysBaseAPI sysBaseAPI = SpringContextUtils.getBean(ISysBaseAPI.class);
			baseCommonService.addLog("SyncUserThreadTask-----同步开始！", CommonConstant.LOG_TYPE_2, null);
			//1、清空工作流相关数据
			IExtActProcessService extActProcessService = SpringContextUtils.getBean(ExtActProcessServiceImpl.class);
			extActProcessService.cleanBpmUser();
			//2、查询需要同步的用户
			 List<UserInfo> list = extActProcessService.getSysUsers();
			 if(list!=null&&list.size()>0){
				    for(UserInfo user:list){
				    	List<RoleInfo> roleList = extActProcessService.getSysRolesByUserId(user.getUuid());
				    	extActProcessService.saveActIdMembership(user, roleList);
				    }
			 }
			SyncUserThreadTask.syncUserFlag = "0";
			log.info("-----SyncUserThreadTask-----同步结束------");
			// 发系统消息通知
			baseCommonService.addLog("SyncUserThreadTask-----同步结束！", CommonConstant.LOG_TYPE_2, null);
			//sysBaseAPI.sendSysAnnouncement(username, username, "同步用户到工作流引擎完成", "同步用户到工作流引擎完成");
			Map<String, String> mp = new HashMap<>();
			mp.put("ts_date",DateUtils.formatDateTime());
			mp.put("ts_content","同步用户到工作流完成！");
			TemplateMessageDTO message = new TemplateMessageDTO(username, username,"用户同步提醒",mp,CommonSendStatus.TZMB_SYS_TS_NOTE);
			sysBaseAPI.sendTemplateAnnouncement(message);
			return true;
		} catch (Exception e1) {
			e1.printStackTrace();
			SyncUserThreadTask.syncUserFlag = "0";
			log.info("-----SyncUserThreadTask-----同步异常------");
		}
		return false;
	}
	

}
